package com.szeastroc.manage.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szeastroc.core.base.controller.BaseController;
import com.szeastroc.core.bean.system.SystemUser;

/**
 * Created by jie on 2018/1/16.
 */
@Controller
public class LoginController extends BaseController{

	@RequestMapping("/login")
	public String index(Model model){
		if( SecurityUtils.getSubject().isAuthenticated()){
			return "main/main.html"; 
		}
		return "login.html";
	}
	
	@RequestMapping("/403")
	public String error403() {
		return "error/403.html";
	}

	/** 
	 * 登录方法 
	 * @param systemUser 
	 * @return 
	 */  
	@PostMapping(value = "/login")    
	public String login(SystemUser systemUser,Model model,HttpServletRequest request) {  
		Subject subject = SecurityUtils.getSubject();  
		UsernamePasswordToken token = new UsernamePasswordToken(systemUser.getUsername(), systemUser.getPassword());  
		try {  
			subject.login(token);  
			return "main/main.html"; 

		} catch (IncorrectCredentialsException e) {   
			model.addAttribute("error", "密码错误");
		} catch (LockedAccountException e) {  
			model.addAttribute("error", "用户已被冻结");
		} catch (AuthenticationException e) {  
			model.addAttribute("error", "用户不存在");
		} catch (Exception e) {  
			logger.error("登录失败",e);  
		}  
		return "login.html"; 
	}  

	@RequestMapping("/home")
	public String main(){
		Object attribute = SecurityUtils.getSubject().getSession().getAttribute("user");  
		System.out.println(attribute);
		return "main/main.html";
	}

	@RequestMapping("/logout")
	public String logOut(HttpSession session) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		session.removeAttribute("user");
		return "login";
	}
}
